package com.src.hb;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.src.hb.model.Timer;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main(String[] args) {
        // Configure the session factory
        //configureSessionFactory();
         
        Session session = null;
        Transaction tx=null;
         
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            
           for(int i=0; i<10000; i++){
        	   Timer t1 = new Timer();
               t1.setTm_active(Boolean.TRUE);
               t1.setTm_hours("00:00|08:00|16:00|");
               t1.setTm_name("Synchronizacja kontaktów"+i);
               t1.setTm_method("TM_SYNC_CONTACTS");
               t1.setTm_interval(Integer.valueOf(3));
               t1.setTm_next_call(new Date(Calendar.getInstance().getTime().getTime()+ t1.getTm_interval().intValue() *60L *1000L));
               session.save(t1);
           }
             
            /*// Creating Contact entity that will be save to the sqlite database
            Contact myContact = new Contact(4, "Piotr", "loter@email.com");
            Contact yourContact = new Contact(5, "Zolter", "zolter17@email.com");
             
            // Saving to the database
            session.save(myContact);
            session.save(yourContact);
            myContact.setEmail("dsfsdf");*/
             
            // Committing the change in the database.
            session.flush();
            tx.commit();
             
            // Fetching saved data
            List<Timer> contactList = session.createCriteria(Timer.class).list();
            TimersExecutor exec = new TimersExecutor();
             
            for (Timer contact : contactList) {
                //System.out.println(contact.toString());
            	exec.execute(contact);
            }
             
        } catch (Exception ex) {
            ex.printStackTrace();
             
            // Rolling back the changes to make the data consistent in case of any failure 
            // in between multiple database write operations.
            tx.rollback();
        } finally{
            if(session != null) {
                session.close();
            }
        }
    }
}
